package com.random.fox.whatspay.greendao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.random.fox.whatspay.greendao.dao.AccountDao;
import com.random.fox.whatspay.greendao.dao.CategoriesDao;
import com.random.fox.whatspay.greendao.dao.CostDao;

import de.greenrobot.dao.AbstractDaoMaster;
import de.greenrobot.dao.identityscope.IdentityScopeType;

/**
 * 它保存了sqlitedatebase对象以及操作DAO classes（注意：不是对象）。
 * Created by 渠 on 2014/11/7.
 */
public class DaoMaster extends AbstractDaoMaster {
    public static final int SCHEMA_VERSION = 1;

    /** Creates underlying database table using DAOs.*/
    public static void createAllTables(SQLiteDatabase db, boolean ifNotExists) {
        AccountDao.createTable(db, ifNotExists);
        CostDao.createTable(db,ifNotExists);
        CategoriesDao.createTable(db,ifNotExists);
    }

    /** Drops underlying database table using DAOs.*/
    public static void dropAllTables(SQLiteDatabase db, boolean ifExists) {
        AccountDao.dropTable(db,ifExists);
        CostDao.dropTable(db,ifExists);
        CategoriesDao.dropTable(db,ifExists);
    }

    public static abstract class OpenHelper extends SQLiteOpenHelper {

        public OpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
            super(context, name, factory, SCHEMA_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            createAllTables(db, false);
        }
    }

    public static class DevOpenHelper extends OpenHelper {
        public DevOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
            super(context, name, factory);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            dropAllTables(db, true);
            onCreate(db);
        }
    }

    public DaoMaster(SQLiteDatabase db) {
        super(db, SCHEMA_VERSION);
        registerDaoClass(AccountDao.class);
        registerDaoClass(CostDao.class);
        registerDaoClass(CategoriesDao.class);
    }

    public DaoSession newSession() {
        return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
    }

    public DaoSession newSession(IdentityScopeType type) {
        return new DaoSession(db, type, daoConfigMap);
    }

}
